package com.example.iread.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.iread.R;
import com.example.iread.activity.SearchResultActivity;
import com.example.iread.application.MyApplication;
import com.example.iread.bean.SearchHistoryBean;
import com.example.iread.dao.SearchHistoryDao;

import java.util.List;

public class SearchHistoryAdapter extends RecyclerView.Adapter<SearchHistoryAdapter.ViewHolder> {

    Context context;

    List<SearchHistoryBean> list;

    SearchHistoryDao searchHistoryDao = MyApplication.getInstance().getDb().searchHistoryDao();

    public SearchHistoryAdapter(Context context, List<SearchHistoryBean> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_history, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setOnClickListener(v -> {
            int adapterPosition = viewHolder.getAdapterPosition();
            SearchHistoryBean searchHistoryBean = list.get(adapterPosition);
            searchHistoryDao.delete(searchHistoryBean);

            Intent intent = new Intent(context, SearchResultActivity.class);
            intent.putExtra("keyword", searchHistoryBean.keyword);
            searchHistoryBean.createTime = System.currentTimeMillis();
            searchHistoryDao.insert(searchHistoryBean);

            context.startActivity(intent);
            ((Activity) context).finish();
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SearchHistoryBean searchHistoryBean = list.get(position);
        holder.tv_search_history.setText(searchHistoryBean.keyword);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView tv_search_history;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_search_history = itemView.findViewById(R.id.tv_search_history);
        }
    }
}
